import axios from 'axios';

// AnythingLLM API 配置
const config = {
    apiKey: '33828WF-8PB4PHT-GDCBR34-68VK7A7',
    baseURL: 'http://192.168.0.80:3003/api/v1/workspace/kefu', // 更新为正确的接口路径
};

// 创建 axios 实例
const anythingllmClient = axios.create({
    baseURL: config.baseURL,
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${config.apiKey}`,
    },
});

// 导出 API 方法
export const anythingllmApi = {
    // 发送消息
    sendMessage: async (message: string, onMessage: (text: string) => void) => {
        try {
            const response = await fetch(`${config.baseURL}/stream-chat`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${config.apiKey}`,
                },
                body: JSON.stringify({ message, mode: 'query' }),
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const reader = response.body?.getReader();
            if (!reader) {
                throw new Error('无法获取响应流');
            }

            const decoder = new TextDecoder();
            let buffer = '';

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                buffer += decoder.decode(value, { stream: true });
                const lines = buffer.split('\n');
                buffer = lines.pop() || '';

                for (const line of lines) {
                    if (line.startsWith('data: ')) {
                        try {
                            const data = JSON.parse(line.slice(6));
                            if (data.textResponse) {
                                onMessage(data.textResponse);
                            }
                        } catch (e) {
                            console.error('解析 SSE 数据失败:', e);
                        }
                    }
                }
            }
        } catch (error) {
            console.error('AnythingLLM API error:', error);
            throw error;
        }
    },
};

export default anythingllmApi; 